package com.epam.web_project.bank.command.customer_commands;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.customer_dao.CustomerDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.exception.SecretAnswerException;
import com.epam.web_project.bank.util.AppPropertiesLoader;

public class AnswerSecretQuestionCommand implements Command {

	private static Logger logger=Logger.getLogger(AnswerSecretQuestionCommand.class);
	
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String resPage;
		AppPropertiesLoader propLoader = AppPropertiesLoader.getInstance();
		String answer = request.getParameter("answer");
		HttpSession session = request.getSession(true);
		if (!session.isNew()) {
			Customer customer = (Customer) session.getAttribute("customerTemp");
			MySQLDAOFactory daoFactory = new MySQLDAOFactory();
			daoFactory.setConnectionPool(ConnectionPool.getInstance());
			CustomerDAO customerDAO = daoFactory.getCustomerDAO();
			Locale locale=request.getLocale();
			ResourceBundle bundle=ResourceBundle.getBundle("i18n", locale);
			if (customerDAO.checkSecret(customer,answer)) {
				resPage = propLoader.getProperty("change_password_page");
			} else {
				logger.warn(propLoader.getProperty("WRONG_SECRET_ANSWER"));
				throw new SecretAnswerException(bundle.getString("java.wrong_ans"));
			}
		} else {
			request.setAttribute("message",
					propLoader.getProperty("NO_CUSTOMER_ID"));
			resPage = propLoader.getProperty("login_page");
		}
		return resPage;
	}

}
